<template>
  <div class="role">
    <div class="role_header">
      <el-form :inline="true" :model="formInline" id="demo_form_inline">
        <el-form-item label="用户名">
          <el-input
            v-model="formInline.user"
            placeholder="请输入用户名"
          ></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <avue-crud
      :option="option"
      :data="managers_list.filter_list"
      @on-load="onLoad"
      :page="page"
    >
      <template #menu="{ row  , size }">
        <el-button
          type="primary"
          :size="size"
          icon="el-icon-edit"
          @click="edit(row)"
          >编辑</el-button
        >
        <el-button
          type="danger"
          :size="size"
          icon="el-icon-delete"
          @click="open(row)"
          >删除</el-button
        >
      </template>
      <template #menu-left="{ size }">
        <el-button type="primary" :size="size" @click="add_list()"
          >新增</el-button
        >
      </template>
    </avue-crud>
    <div v-show="flags" class="Mask_layer">
      <div class="div_ipt">
        <div class="close_div">
          <span>{{ titles == "新增" ? "新增" : "编辑" }}</span>

          <span
            class="hoverhe"
            @click="
              () => {
                flags = false;
              }
            "
            >X</span
          >
        </div>
        <div class="paramster_ipts">
          <el-form
            ref="ruleFormRef"
            :model="ruleForm"
            :rules="rules"
            label-width="120px"
            class="demo-ruleForm"
            :size="formSize"
            status-icon
          >
            <el-form-item label="用户名" prop="name">
              <el-input
                v-model="ruleForm.name"
                size="large"
                class="input_one"
              />
            </el-form-item>
            <el-form-item label="密码" prop="pass">
              <el-input
                v-model="ruleForm.pass"
                type="password"
                autocomplete="off"
                class="input_one"
              />
            </el-form-item>
            <el-form-item label="确认密码" prop="checkPass">
              <el-input
                v-model="ruleForm.checkPass"
                type="password"
                autocomplete="off"
                class="input_one"
              />
            </el-form-item>
            <el-form-item prop="Email" label="邮箱">
              <el-input v-model="ruleForm.email" class="input_one" />
            </el-form-item>
            <el-form-item label="手机号" prop="phone">
              <el-input
                v-model="ruleForm.phone"
                size="large"
                class="input_one"
              />
            </el-form-item>
            <el-form-item label="角色" prop="type">
              <el-checkbox-group
                v-model="ruleForm.type"
                label="Online activities"
                name="type"
                v-for="(item, index) in managers_list.flag_list"
                :key="index"
                @change="log_value(item)"
              >
                <el-checkbox
                  :label="item.roleName"
                  name="type"
                  style="padding-left: 15px"
                />
                <!-- <el-checkbox label="Promotion activities" name="type" />
                <el-checkbox label="Offline activities" name="type" />
                <el-checkbox label="Simple brand exposure" name="type" /> -->
              </el-checkbox-group>
            </el-form-item>
            <el-form-item label="状态" prop="resource">
              <el-radio-group v-model="ruleForm.resource">
                <el-radio label="禁用" />
                <el-radio label="正常" />
              </el-radio-group>
            </el-form-item>

            <!-- <el-form-item>
              <el-button type="primary" @click="submitForm(ruleFormRef)"
                >Create</el-button
              >
              <el-button @click="resetForm(ruleFormRef)">Reset</el-button>
            </el-form-item> -->
          </el-form>
        </div>
        <div class="footers">
          <span
            @click="
              () => {
                flags = false;
              }
            "
            >取消</span
          >
          <span class="blues" @click="add_lists(ruleFormRef)">确定</span>
        </div>
      </div>
    </div>
  </div>
</template>


<script setup lang="ts">
import { ref } from "vue";
import managers from "../../../../store/managers";
import { ElMessage, ElMessageBox } from "element-plus";
const managers_list = managers();
import { reactive } from "vue";

import type { FormInstance, FormRules } from "element-plus";

const formSize = ref("default");
const ruleFormRef = ref<FormInstance>();
let checkdata = [];
let filtercheckdata = [];
const ruleForm = reactive({
  name: "",
  pass: "",
  checkPass: "",
  delivery: false,
  type: [],
  resource: "正常",
  desc: "",
  phone: "",
  email: "",
  userId: "",
});

let formInline: any = ref({
  user: "",
  region: "",
});
let flags = ref(false);
let titles: any = "新增";

let page: any = {
  currentPage: 1,
  pageSize: 10,
};
let option: any = {
  delBtn: false,
  editBtn: false,
  excelBtn: true,
  selection: true,
  selectionWidth: 100,
  addBtn: false,
  selectionFixed: false,
  border: true,
  expandLevel: 3,
  headerAlign: "center",
  align: "center",
  tree: true,
  labelWidth: 100,
  column: [
    {
      // width: 130,
      label: "用户名",
      prop: "username",
      display: false,
    },
    {
      label: "邮箱",
      prop: "email",
      display: false,
    },
    {
      label: "手机号",
      prop: "mobile",
      display: false,
    },
    {
      label: "创建时间",
      prop: "createTime",
      display: false,
    },
    {
      label: "状态",
      prop: "icon",
      html: true,
      formatter: (row) => {
        return row.status == 1
          ? '<span class="status1">启用</span>'
          : "<span class='status2'>未启用</span>";
      },
      display: false,
    },
  ],
};

const getlist = () => {
  managers_list.managers_getlist();
};
getlist();
const onLoad = (page: any) => {
  //模拟分页
  page.total = managers_list.list_Len;
  console.log(managers_list.list_Len, "managers_list.list_Len");
};

interface DomainItem {
  key: number;
  value: string;
}

const dynamicValidateForm = reactive<{
  domains: DomainItem[];
  email: string;
}>({
  domains: [
    {
      key: 1,
      value: "",
    },
  ],
  email: "",
});

const log_value = (e) => {
  console.log(e, "53213213");
  let arr = [];
  let ind = 0;
  if (checkdata.length == 0) {
    checkdata.push(e.roleId);
  } else {
    checkdata.forEach((item, index) => {
      if (item == e.roleId) {
        ind = index;
        arr.push(e.roleId);
      }
    });

    if (arr.length == 0) {
      checkdata.push(e.roleId);
    } else {
      checkdata.splice(ind, 1);
    }
  }
  console.log(checkdata, "checkdata");
};

//编辑
const edit = (row: any) => {
  titles = "编辑";
  managers_list.managers_getflaglist();
  console.log(row, "rwo");
  ruleForm.name = row.username;
  ruleForm.email = row.email;
  ruleForm.phone = row.mobile;
  ruleForm.resource = row.status == 1 ? "正常" : "禁用";
  ruleForm.userId = row.userId;
  flags.value = true;
};

//判断输入密码框是否为空
const validatePass = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("确定密码不能为空"));
  } else {
    if (ruleForm.checkPass !== "") {
      if (!ruleFormRef.value) return;
      ruleFormRef.value.validateField("checkPass", () => null);
    }
    callback();
  }
};

//判断确认密码框输入是否为空 并且判断输入是否和密码框相同
const validatePass2 = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("确认密码不能为空"));
  } else if (value !== ruleForm.pass) {
    callback(new Error("确认密码与密码输入不一致"));
  } else {
    callback();
  }
};

const rules = reactive<FormRules>({
  name: [{ required: true, message: "用户名不能为空", trigger: "blur" }],

  resource: [
    {
      required: true,
      message: "Please select activity resource",
      trigger: "change",
    },
  ],
  desc: [
    { required: true, message: "Please input activity form", trigger: "blur" },
  ],
  pass: [{ validator: validatePass, trigger: "blur" }],
  checkPass: [{ validator: validatePass2, trigger: "blur" }],
  email: [
    {
      required: true,
      message: "Please input email address",
      trigger: "blur",
    },
    {
      type: "email",
      message: "Please input correct email address",
      trigger: ["blur", "change"],
    },
  ],
  phone: [{ required: true, message: "手机号不能为空", trigger: "blur" }],
});

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
    } else {
      console.log("error submit!", fields);
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

// const options = Array.from({ length: 10000 }).map((_, idx) => ({
//   value: `${idx + 1}`,
//   label: `${idx + 1}`,
// }));

const add_list = () => {
  managers_list.managers_getflaglist();
  console.log(managers_list.flag_list);

  flags.value = true;
  titles = "新增";
};

//新建弹框中的确认按钮
const add_lists = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (titles == "新增") {
        console.log(ruleForm);
        managers_list.add_list({
          name: ruleForm.name,
          pass: ruleForm.pass,
          checkPass: ruleForm.checkPass,
          email: ruleForm.email,
          phone: ruleForm.phone,
          type: checkdata,
          resource: ruleForm.resource,
        });
        flags.value = false;
      } else {
        managers_list.edit_list({
          name: ruleForm.name,
          pass: ruleForm.pass,
          checkPass: ruleForm.checkPass,
          email: ruleForm.email,
          phone: ruleForm.phone,
          type: checkdata,
          resource: ruleForm.resource,
          userId: ruleForm.userId,
        });
        flags.value = false;
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};

//查找
const onSubmit = () => {
  managers_list.search_list(formInline.value.user);
  // console.log(formInline.value.user, "formInline.user");
};

//删除
const open = (obj: any) => {
  ElMessageBox.confirm(`确定对[${obj.userId}]进行[删除]操作吗`, "删除", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      managers_list.del_list(obj.userId);
      // ElMessage({
      //   type: "success",
      //   message: "Delete completed",
      // });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消操作",
      });
    });
};
</script>
<style>
@import "./managers.css";
</style>